import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store';
import {
  Toast
} from 'vant';

Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      isRoot: true,
    }
  },
  {
    path: '/my',
    name: 'my',
    component: () => import('../views/My.vue'),
    meta: {
      isRoot: true,
    }
  },
  {
    path: '/publish',
    name: 'publish',
    component: () => import('../views/Publish.vue'),
    meta: {
      isRoot: true,
    
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),

  },
  {
    path: '/reg',
    name: 'Reg',
    component: () => import('../views/Reg.vue'),

  },
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('../views/Detail/Detail.vue'),

  },
  {
    path: '/userInfo',
    name: 'UserInfo',
    component: () => import('../views/UserInfo.vue'),
    meta: {
      privacy: true
    }

  },
  {
    path: '/forget',
    name: 'Forget',
    component: () => import('../views/Forget.vue'),

  },
  {
    path: '/updatePwd',
    name: 'UpdatePwd',
    component: () => import('../views/UpdatePwd.vue'),
    meta: {
      privacy: true
    }

  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/search/Search.vue'),

  },
  {
    path: '/list',
    name: 'list',
    component: () => import('../views/search/list.vue'),

  },
  {
    path: '/myFav',
    name: 'myFav',
    component: () => import('../views/myFav.vue'),
    meta: {
      privacy: true
    }

  },
  {
    path: '/myPublish',
    name: 'myPublish',
    component: () => import('../views/myPublish.vue'),
    meta: {
      privacy: true
    }

  },

]

const router = new VueRouter({
  routes

})


//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


router.beforeEach((to, from, next) => {

  if (to.meta.privacy) {
    let hasLogin = store.state.users.hasLogin
    if (hasLogin) {
      next()
    } else {
      Toast('请先登录')
      setTimeout(() => {
        next('/login')
      }, 1000);
    }
  } else {
    next()
  }
})

export default router